<?php

/**
 * Truncate view helper
 *
 * @category    Ext
 * @package     Ext_View
 * @subpackage  Ext_View_Helper
 */
class Ext_View_Helper_Truncate extends Zend_View_Helper_Abstract
{
    /**
     *
     * @param string $str
     * @param int $n truncate string to $n chars
     * @param string $endChar
     * @return string
     */
    public function truncate($str, $n = 500, $endChar = '&#8230;')
    {
        if (strlen($str) < $n) {
            return $str;
        }

        $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));

        if (strlen($str) <= $n) {
            return $str;
        }

        $out = '';
        foreach (explode(' ', trim($str)) as $val) {
            $out .= $val . ' ';

            if (strlen($out) >= $n) {
                $out = trim($out);
                return (strlen($out) == strlen($str)) ? $out : $out . $endChar;
            }
        }
    }
}